import styles from './index.module.scss'
import { NavBar, Form, Input, Button, List, Toast } from 'antd-mobile'
import { useRef, useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { login, getCode } from '@/store/actions/login'
import { InputRef } from 'antd-mobile/es/components/input'

export default function Login() {
  const history = useHistory()
  const location = useLocation<{ from: string }>()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  // ref用于存储定时器id
  const timeRef = useRef(-1)
  const [time, setTime] = useState(0)


  // 登录
  const onFinish = async (values: LoginForm) => {
    await dispatch(login(values))
    Toast.show({
      content: '登录成功',
      duration: 600,
      afterClose: () => {
        // history.push('/home')
        let pathname = location.state ? location.state.from : '/home'
        history.replace(pathname)
      }
    })
  }
  // 获取验证码
  const onGetCode = async () => {
    // 获取手机号
    const mobile = form.getFieldValue('mobile')
    // 获取手机号对应的校验错误
    const error = form.getFieldError('mobile')
    if (!mobile || error.length > 0) {
      // 手机号不完整
      mobileRef.current?.focus()
      return
    }
    await dispatch(getCode(mobile))
    setTime(5)
    timeRef.current = window.setInterval(() => {
      setTime(time => time - 1)
    }, 1000)
  }
  useEffect(() => {
    if (time === 0) {
      // 时间到了
      clearInterval(timeRef.current)
    }
  }, [time])

  // 组件销毁的时候，清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timeRef.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>
      <div className="login-form">
        <h2 className="title">短信登录</h2>
        <Form
          form={form}
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810'
          }}
          footer={
            <Button
              color="primary"
              block
              className="login-submit"
              type="submit"
            >
              登录
            </Button>
          }>
          <Form.Item className="login-item"
            name="mobile"
            rules={[
              {
                required: true,
                message: '手机号不能为空'
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误'
              }
            ]}>
            <Input placeholder="请输入手机号" ref={mobileRef}></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra"
                onClick={onGetCode}>
                {time === 0 ? '发送验证码' : `${time}s后再次发送`}
              </span>}
          >
            <Form.Item className="login-item"
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空'
                },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式错误'
                }
              ]}>
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
        </Form>
      </div>
    </div>
  )
}
